import React, { Component } from 'react';
import moment from 'moment';
import XLSX from 'xlsx';
import {
  Tooltip,
  Card,
  Button,
  Table,
  Tag,
  Modal,
  Typography,
  message
} from 'antd';
import { getArticals, deleteArticle } from '../../requests';
import { SetData } from '../commom';
const ButtonGroup = Button.Group;
const { Text } = Typography;
const titleDisplayMap = {
  //灵活使用map匹配
  id: 'id',
  title: '标题',
  author: '作者',
  createAt: '创建时间',
  amount: '阅读量'
};
export default class ArticalList extends Component {
  constructor() {
    super();
    this.state = {
      total: 0,
      columns: [],
      data: [],
      isLoading: false,
      offset: 0,
      limited: 10,
      ArticleModalTitle: null,
      visible: false,
      deleteArticleConfirmLoading: false,
      currentDeleteId: null
    };
  }
  createColumns = res => {
    const columns = Object.keys(res.data.list[0]).map(item => {
      if (item === 'amount') {
        return {
          title: titleDisplayMap[item],
          render: (text, record) => {
            //text：当前行的好值
            //record：当前行数据
            //修改dataIndex
            return (
              <Tooltip
                title={record.amount > 200 ? '阅读量上升' : '阅读量下降'}
              >
                <Tag color={record.amount > 200 ? 'red' : 'green'}>
                  {record.amount}
                </Tag>
              </Tooltip>
            );
          }, //需要一一对应是的关系
          key: item
        };
      }
      if (item === 'createAt') {
        return {
          title: titleDisplayMap[item],
          key: item,
          render: (text, record) => {
            const { createAt } = record;
            return moment(createAt).format('YYYY-MM-DD HH:mm:ss'); // HH:mm:ss：HH是24小时制
          }
        };
      }
      return {
        title: titleDisplayMap[item],
        dataIndex: item,
        key: item
      };
    });
    //render里面的函数需要绑定this
    columns.push({
      title: '操作',
      key: 'action',
      render: (text, record) => {
        //这里一定要写成匿名函数的格式呢
        //参数：当前行的值，当前行的数据
        return (
          <ButtonGroup>
            <Button
              size="small"
              type="primary"
              onClick={this.toEdit.bind(this, record)}
            >
              编辑
            </Button>
            <Button
              size="small"
              type="danger"
              onClick={this.deleteArtical.bind(this, record)}
            >
              删除
            </Button>
          </ButtonGroup>
        );
      }
    });
    return columns;
  };
  toEdit = record => {
    this.props.history.push({
      pathname: `/admin/artical/edit/${record.id}`,
      state: {
        //加密传参
        title: record.title
      }
    });
  };
  deleteArtical = record => {
    this.setState({
      ArticleModalTitle: (
        <Text>
          确认要删除<span style={{ color: 'red' }}>{record.title}</span>吗？
        </Text>
      ),
      visible: true,
      currentDeleteId: record.id
    });
  };
  hideDeleteModal = () => {
    this.setState({
      visible: false
    });
  };
  getData = () => {
    this.setState({
      isLoading: true
    });
    getArticals(this.state.offset, this.state.limited)
      .then(res => {
        const columns = this.createColumns(res);
        SetData.bind(this, {
          total: res.total,
          columns,
          data: res.data.list,
          isLoading: false
        });
      })
      .catch(err => {
        //处理错误
      })
      .finally(() => {
        //finaly里面是一个回调函数
        SetData.bind(this, {
          isLoading: false
        });
      });
  };
  onPageChange = (page, pageSize) => {
    this.setState(
      {
        //this.setState第二个参数是一个回调
        offset: pageSize * (page - 1), //表示从第几条数据开始获取
        limited: pageSize
      },
      () => {
        this.getData();
      }
    );
  };
  //当请求的页码发生变化时
  onShowSizeChange = (current, size) => {
    this.setState(
      {
        offset: 0,
        limited: size
      },
      () => {
        this.getData();
      }
    );
  };
  toExcel = () => {
    //导出excel：实际工作中是发送请求给后端，后端返回一个文件下载的地址
    //https://github.com/SheetJS/sheetjs/blob/a81bb78f18960053a03bb3350f31ea54d28245be/demos/react/sheetjs.jsx
    /* convert state to workbook */
    const data = [Object.keys(this.state.data[0])];
    for (let i = 0; i < this.state.data.length; i++) {
      // data.push(Object.values(this.state.data[i]));//这样写的话，对象是无序的，可能不是对应关系
      const { id, title, author, amount, createAt } = this.state.data[i];
      data.push([
        id,
        title,
        author,
        amount,
        moment(createAt).format('YYYY-MM-DD HH:mm:Ss')
      ]);
    }
    const ws = XLSX.utils.aoa_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'SheetJS');
    /* generate XLSX file and send to client */
    XLSX.writeFile(
      wb,
      `articals${this.state.offset / this.state.limited + 1}.xlsx`
    );
  };
  comfirmDeleteArticle = () => {
    this.setState({
      deleteArticleConfirmLoading: true
    });
    deleteArticle(this.state.currentDeleteId)
      .then(res => {
        if (res.code === 200) {
          this.setState({
            deleteArticleConfirmLoading: false
          });
          message.success(res.data.msg);
          //返回之前点击的那一页
          //第一页
          // this.setState({
          //   offset:0
          // }, () => {
          //   this.getData();
          // })
          let { offset, limited } = this.state;
          this.getData(offset, limited);
        }
      })
      .catch(err => {
        message.error(err);
      })
      .finally(() => {
        //完成之后关闭弹框
        this.hideDeleteModal();
      });
  };
  componentDidMount() {
    this.getData();
  }
  render() {
    let {
      total,
      data,
      columns,
      isLoading,
      offset,
      limited,
      ArticleModalTitle,
      visible,
      deleteArticleConfirmLoading
    } = this.state;
    return (
      <>
        <Card
          style={{ width: '100%' }}
          title="文章列表"
          extra={<Button onClick={this.toExcel}>导出excel</Button>}
          bordered={false}
        >
          <p>Card content</p>
          <p>Card content</p>
          <p>Card content</p>
        </Card>
        <Table
          rowKey={record => record.id}
          columns={columns}
          dataSource={data}
          loading={isLoading}
          pagination={{
            total,
            current: offset / limited + 1,
            showSizeChanger: true,
            hideOnSinglePage: true, //只有一页时是否隐藏分页器.
            showQuickJumper: true,
            onChange: this.onPageChange,
            onShowSizeChange: this.onShowSizeChange
          }}
        />
        <Modal
          title={ArticleModalTitle}
          visible={visible}
          onCancel={this.hideDeleteModal}
          onOk={this.comfirmDeleteArticle}
          confirmLoading={deleteArticleConfirmLoading}
        >
          该操作不可逆，请谨慎操作！
        </Modal>
      </>
    );
  }
  //rowKey: (record)=>record.id，key为当前数据的id
}
